﻿(function (Helper) {
'use strict';

    Helper.CurServerIP = null;

    Helper.GetServerIP = function () {
        if(Helper.CurServerIP!=null&&Helper.CurServerIP!="http://false"){
            return Helper.CurServerIP;
        }
        var serverIP = localStorage.getItem("serverIP");
        if (serverIP == null || serverIP=="") {
            serverIP = "https://arbs.world/web";
        }
        return serverIP;
    }

    Helper.SetServerIP = function (serverIP) {
        localStorage.setItem("serverIP", serverIP);
    }

    // 地址栏参数
    Helper.getQueryVariable = function(variable, search) {
        if (search == null)
            search = window.location.search;
        var query = search.substring(1);
        var vars = query.split("&");
        for (var i = 0; i < vars.length; i++) {
            var pair = vars[i].split("=");
            if (pair[0] == variable) { return pair[1]; }
        }
        return (false);
    }

    Helper.checkPlatform = function () {
        const ua = navigator.userAgent.toLowerCase();
        const testUa = regexp => regexp.test(ua);

        // 系统
        let system = "unknown";
        if (testUa(/windows|win32|win64|wow32|wow64/ig)) {
            system = "Windows"; // window系统
        } else if (testUa(/macintosh|macintel/ig)) {
            system = "MAC OS"; // MAC OS系统
        } else if (testUa(/x11/ig)) {
            system = "Linux"; // Linux系统
        } else if (testUa(/android|adr/ig)) {
            system = "Android"; // Android系统
        } else if (testUa(/ios|iphone|ipad|ipod|iwatch/ig)) {
            system = "IOS"; // IOS系统
        }

        if (system == "Windows" || system == "MAC OS" || system == "Linux") {
            return "pc";
        } else {
            return "phone";
        }
    }

    Helper.isPortrai = function() { // 竖屏
        if(window.innerWidth<500){
            return true;
        }
        return false;
    }

    Helper.Simplify = function (str,p) {
        if( !str ) return '';
        if( !p&&Helper.checkPlatform() == "pc" ) {
            return str;
        }
        return str.slice(0, 12) + "..." + str.slice(str.length - 6, str.length)
    }

    Helper.Simplify2 = function (str,p) {
        if (!p&&Helper.checkPlatform() == "pc") {
            return str;
        }
        return str.slice(0, 8) + "..." + str.slice(str.length - 6, str.length)
    }

    Helper.Simplify3 = function (str,p) {
        if (!p&&Helper.checkPlatform() == "pc") {
            return str;
        }
        return str.slice(0, 4) + "..." + str.slice(str.length - 4, str.length)
    }    

    Helper.hashCode = function(str) {
        var hash = 0;
        if (str.length == 0) {
            return hash;
        }
        for (var i = 0; i < str.length; i++) {
            var char = str.charCodeAt(i);
            hash = ((hash<<5)-hash)+char;
            hash = hash & hash; // Convert to 32bit integer
        }
        return hash;
    }

    Helper.formatDate = function(date) {
        var date = new Date(date);
        var YY = date.getFullYear() + '-';
        var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-';
        var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate());
        var hh = (date.getHours() < 10 ? '0' + date.getHours() : date.getHours()) + ':';
        var mm = (date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes()) + ':';
        var ss = (date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds());
        return YY + MM + DD + " " + hh + mm + ss;
    }

    Helper.hide_popover = function(id) {
        var popover = document.getElementsByClassName("popover fade show bs-popover-bottom");
        if (popover.length >= 1)
            document.getElementById(id).click();
    }

    // 复制到剪切板
    Helper.hide_popover_timer = null;

    Helper.copyToClipBoard = function(id) {
        console.log("copyToClipBoard",$("#"+id).val());

        navigator.clipboard.writeText($("#"+id).val());

        clearTimeout(Helper.hide_popover_timer);
        Helper.hide_popover_timer = setTimeout("Helper.hide_popover('btnCopyToClip')", 5000);
    };

    Helper.modal = function(id,b,c){
        var myModalEl = document.getElementById(id)
        var modal = new bootstrap.Modal(myModalEl,c) // initialized with defaults
        if(b=='show')
            modal.show();
        else
            modal.hide();
    }

    Helper.Mul = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.multipliedBy(bb).toString().replace(/,/g, "");
    }
    Helper.Div = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.dividedBy(bb).toString().replace(/,/g, "");
    }
    Helper.Add = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.plus(bb).toString().replace(/,/g, "");
    }
    Helper.Sub = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.minus(bb).toString().replace(/,/g, "");
    }
    Helper.isGreater = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.isGreaterThan(bb);
    }
    Helper.isGreaterThanOrEqualTo = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.isGreaterThanOrEqualTo(bb);
    }    
    Helper.isLessThan = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.isLessThan(bb);
    }
    Helper.isLessThanOrEqualTo = function (aa,bb) {
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        if(typeof(bb)=='string')
            bb = new BigNumber(bb.replace(/,/g, ""));
        return aa.isLessThanOrEqualTo(bb);
    }    
    Helper.Fix = function (aa) {
        if(aa==null||aa=="")
            aa = "0"
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        aa = new BigNumber(aa.toString().replace(/,/g, ""));
        if (aa == "NaN")
            aa = new BigNumber(0);
        if (aa == "Infinity")
            aa = new BigNumber(0);
        return aa.toFormat().replace(/,/g, "");
    }

    Helper.Fix2 = function (aa) {
        return Helper.FixDecimal(aa,2)
    }

    Helper.Fix4 = function (aa) {
        return Helper.FixDecimal(aa,4)
    }

    Helper.Fix8 = function (aa) {
        return Helper.FixDecimal(aa,8)
    }

    Helper.FixDecimal = function (aa,decimal) {
        if(aa==null||aa=="")
            aa = "0"
        if(typeof(aa)=='string')
            aa = new BigNumber(aa.replace(/,/g, ""));
        aa = new BigNumber(aa.toFixed(decimal, 1).replace(/,/g, ""));
        if (aa == "NaN")
            aa = new BigNumber(0);
        if (aa == "Infinity")
            aa = new BigNumber(0);
        return aa.toFormat().replace(/,/g, "");
    }

    // input type="text" 否则无效
    Helper.getSelectPosition = function (oTxt){
        var nullvalue = -1;
        var selectStart ;//选中开始位置
        var selectEnd ;//选中结束位置
        var position;//焦点位置
        var selectText;//选中内容
        if(oTxt.setSelectionRange){//非IE浏览器
            selectStart= oTxt.selectionStart;
            selectEnd = oTxt.selectionEnd;
            if(selectStart == selectEnd){
                position = oTxt.selectionStart;
                selectStart = nullvalue;
                selectEnd = nullvalue;
            }else{
                position = 	nullvalue;
            }
            selectText = oTxt.value.substring(selectStart,selectEnd);
        }else{//IE
            var range = document.selection.createRange();
            selectText=range.text;
            range.moveStart("character",-oTxt.value.length);
            position = range.text.length;
            selectStart = position - (selectText.length);
            selectEnd = selectStart + (selectText.length);
            if(selectStart != selectEnd){
                position = nullvalue;
            }else{
                selectStart = nullvalue;
                selectEnd = nullvalue;
            }
        }
        return position;
    }

    Helper.TableInsertRecord = function () {
        var innerHTML = "\
                        <tbody>\
                        <tr id='myid' onclick='liOnRecordclick(this)'>\
                            <th>\
                            <h6>\
                                存款 USDT\
                            </h6>\
                            <h6 style='color: #7c7c7c;'>\
                                日期\
                            </h6>\
                            </th>\
                            <th style='text-align: center;'>\
                            <h6>\
                                额度\
                            </h6>\
                            <h6 style='color: #7c7c7c;'>\
                                状态\
                            </h6>\
                            </th>\
                        </tr>\
                        </tbody>\
                        "

        innerHTML = innerHTML.replace(/myid/g, arguments[1]);
        innerHTML = innerHTML.replace(/存款/g, arguments[2]);
        innerHTML = innerHTML.replace(/USDT/g, arguments[3]);
        innerHTML = innerHTML.replace(/日期/g, arguments[4]);
        innerHTML = innerHTML.replace(/额度/g, arguments[5]);
        innerHTML = innerHTML.replace(/状态/g, arguments[6]);

        var item_new = document.createElement("tbody");
        console.log( arguments[0] );
        item_new.innerHTML = innerHTML;
        document.getElementById(arguments[0]).appendChild(item_new);
    }

    Helper.TableInsertBettingSlip = function () {
        var innerHTML = '\
                        <tbody>\
                            <tr id="myid" onclick="liOnclick(this)">\
                                <td>type</td>\
                                <td>amount</td>\
                                <td>state</td>\
                                <td>time</td>\
                            </tr>\
                        </tbody>\
                        ';

        innerHTML = innerHTML.replace(/myid/g, arguments[1]);
        innerHTML = innerHTML.replace(/type/g, arguments[2]);
        innerHTML = innerHTML.replace(/amount/g, arguments[3]);
        innerHTML = innerHTML.replace(/state/g, arguments[4]);
        innerHTML = innerHTML.replace(/time/g, arguments[5]);
        if(arguments[6]%2==1){
            innerHTML = innerHTML.replace(/class='table-color'/g, '');
        }

        var item_new = document.createElement("tbody");
        console.log( arguments[0] );
        item_new.innerHTML = innerHTML;
        document.getElementById(arguments[0]).appendChild(item_new);
    }

    //async
    Helper.sleep = async function (time) {
        return new Promise(resolve => setTimeout(resolve, time));
    }

    Helper.addressCur = null;
    Helper.provider = null;//创建一个Provider
    Helper.sessionToken = "";

    Helper.GetLastLoginInfo = function (address) {
        var       nonces = localStorage.getItem(address+"#LastLoginInfo_nonces");
        var sessionToken = localStorage.getItem(address+"#LastLoginInfo_sessionToken");
        // var       nonces = sessionStorage.getItem(address+"#LastLoginInfo_nonces");
        // var sessionToken = sessionStorage.getItem(address+"#LastLoginInfo_sessionToken");
        return {nonces:nonces,sessionToken:sessionToken};
    }

    Helper.SetLastLoginInfo = function (address,nonces,sessionToken) {
        localStorage.setItem(address+"#LastLoginInfo_nonces"      , nonces);
        localStorage.setItem(address+"#LastLoginInfo_sessionToken", sessionToken);
        // sessionStorage.setItem(address+"#LastLoginInfo_nonces"      , nonces);
        // sessionStorage.setItem(address+"#LastLoginInfo_sessionToken", sessionToken);
    }

    Helper.popoverTriggerList = null;

    Helper.ConnectWallet = async function (address)
    {
        console.log("Helper.ConnectWallet");

        if(Helper.provider==null) {
            if (typeof window.ethereum != 'undefined') {
                Helper.provider = new window._ethers.providers.Web3Provider(window.ethereum)
            }
            else
            if(typeof window.web3 != 'undefined'){
                Helper.provider = new window._ethers.providers.Web3Provider(window.web3.currentProvider);
            }
            console.log("Helper.provider = " + Helper.provider);
        }

        if(Helper.addressCur==null) {
            if (Helper.provider==null) {
                $('#btn_head_ConnectWallet').show();
                //setTimeout(function () { Helper.Init() }, 300);
            }
            else {
                // app init code
                await Helper.connect_to_metamask(address);
                return;
            }
        }
    }

    /**
     * 连接metamask钱包，获取余额
     */
    Helper.connect_to_metamask = async function (paramAddress)
    {
        console.log("connect_to_metamask 1");
        try
        {
            console.log("connect_to_metamask 2");

            //向钱包发送授权请求
            if(paramAddress==null){
                let accounts = undefined;
                try {
                    accounts = await Helper.provider.send("eth_requestAccounts", []);
                }
                catch(e){ console.log(e); return; }
                console.log("connect_to_metamask 3");

                if( accounts && accounts.length==0 ) {
                    alert("请将钱包切换至Arbitrum One,或者其他以太坊系列网络。");
                    return;
                }
                console.log("connect_to_metamask accounts = "+accounts);
                if (accounts && accounts.length > 0) {
                    paramAddress = accounts[0];
                }
            }

            //获取账户余额信息
            if (paramAddress!=null) {
                var addressQuery = Helper.getQueryVariable("address") || paramAddress;

                Helper.addressCur = addressQuery;
                console.log("当前账户地址：", Helper.addressCur);
                
                $('#head_navbar_center').show();
                $('#btn_head_Search').show();
                $('#btn_head_Setting').show();
                $('#btn_head_Orders').show();
                $('#btn_head_ConnectWallet').hide();

                if(onLogin!=undefined){
                    onLogin();
                }
            }
        }
        catch(e)
        {
            console.log(e);
        }

        if(Helper.addressCur==null){
            $('#btn_head_ConnectWallet').show();
        }

    }

    Helper.MakeVisitor = function ()
    {
        var address = localStorage.getItem("VisitorAddress");
        if(address==undefined){
            let lbcWallet = window._ethers.Wallet.createRandom();
            address = lbcWallet.address;
            localStorage.setItem("VisitorAddress",address);
        }
        return address;
    }

    Helper.SetInviter = function ()
    {
        if(Helper.inviter==null||Helper.inviter==undefined||Helper.inviter==""){
            return;
        }

        var inviter = localStorage.getItem(Helper.addressCur+"#inviter");
        if(inviter!=null&&inviter!=undefined&&inviter!=""){
            Helper.inviter = inviter;
            return;
        }

        $.ajax({
          url: Helper.GetServerIP() + "/Inviter",
                    dataType: "text",
                    type: "post",
                    data: {address: Helper.addressCur,sessionToken:Helper.sessionToken,inviter:Helper.inviter},
                    success: function (data) {
                        if (data.indexOf("error") == -1) {
                            localStorage.setItem(Helper.addressCur+"#inviter", data);
                        }
                    },
                    error: function (err) {
                      console.log(err);
                    }
        });
    }

    

})(typeof module !== 'undefined' && module.exports ? module.exports : (self.Helper = self.Helper || {}));